<?php
    namespace app\index\controller;
    use think\Exception;
    use yaliSDK\common\Constrants;
    use yaliSDK\common\Result;
    use yaliSDK\user\UserService;
    use yaliSDK\utils\Json;
    use yaliSDK\utils\WXHelper;

    class User {
        /**
         * 角色为商家，消费者，网红
         * 用户授权，传入openid，检查用户是否注册，
         * 1.没注册的用户，默认自动注册，角色为消费者；
         * 2.已注册用户，判断是消费者，商家还是网红
         */
        function authorize() {
            $inputJSON = file_get_contents('php://input');
            $params = json_decode($inputJSON, TRUE) ?? [];

            $code = $params['code'] ?? null;
            $appid = $params['appid'] ?? null;
            $roleType = $params['roleType'] ?? null;// 用户端，门店，主播
            $wxinfo = WXHelper::getWxInfoByCode($code, WXHelper::getWXSetByAppId($appid));// 读取直播的配置项
            // 授权成功
            try {
                if (!empty($wxinfo) && property_exists($wxinfo, 'openid')) {
                    $openid = $wxinfo->openid ?? null;

                    $usesS = new UserService();
                    $result = $usesS->userDetail($openid, ['key' => 'openid']);
                    $user = Result::_getInstanceData($result);

                    // 用户找不到
                    if (empty($user)) {
                        return Json::classToArray(new Result(null, Constrants::$NO_EXIST));
                    }

                    $_res = [];// 返回结果
                    $_res['user'] = $user;
                    $_res['role'] = Constrants::$ROLE_USER;
                    return Json::classToArray(new Result($_res));

                } else {
                    return Json::classToArray(new Result('无openid', Constrants::$NO_EXIST));
                }

            } catch (Exception $e) {
                return Json::classToArray(new Result($e->getMessage()));
            }
        }
    }